package com.lanou.moving.activity;

import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.lanou.moving.R;
import com.lanou.moving.adapter.FragmentAdapter;
import com.lanou.moving.base.BaseActivity;
import com.lanou.moving.base.BaseApplication;
import com.lanou.moving.fragment.BackHandledFragment;
import com.lanou.moving.fragment.BackHandledInterface;
import com.lanou.moving.receiver.ServiceReceiver;
import com.lanou.moving.residemenu.ResideMenu;
import com.lanou.moving.residemenu.ResideMenuItem;
import com.lanou.moving.service.MyService;
import com.lanou.moving.utils.SkinSettingManager;
import com.lanou.moving.view.DataCleanManager;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;


/**
 * Created by dllo on 15/10/20.
 **/

public class MainActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener, BackHandledInterface {

    private TabLayout main_tablayout;
    private ImageView main_menu;
    private ImageView main_search;
    private ResideMenu main_residemenu;// 弹出的menu
    public static final String ALARM_CLOCK_BROADCAST = "alarm_clock_broadcast";//睡眠模式
    private RelativeLayout layout;
    private SkinSettingManager mSettingManager;


    private ResideMenuItem itemLucency;// 透明模式
    private ResideMenuItem itemWallpaper;// 壁纸&皮肤
    private ResideMenuItem itemSetting;// 设置
    private ResideMenuItem itemSleep;// 睡眠
    private ResideMenuItem itemExit;// 退出应用
    private int mScreenWidth;// 屏幕宽度

    private boolean is_closed = true;// 判断resideMenu是否关闭
    private long mExitTime;
    private ViewPager main_viewpager;

    private UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");

    private BackHandledFragment mBackHandedFragment;
    private ServiceReceiver receiver;
    public static final String SP_SHAKE_CHANGE_SONG = "shake_change_song";
    private String size;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BaseApplication.getInstance().addActivity(this);
        layout = (RelativeLayout) findViewById(R.id.mulayout);

        // 初始化Menu
        setUpMenu();
        // 给Menu的Item设置监听
        setListener();
        // 注册广播
        register();

        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels;
        // 注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(ALARM_CLOCK_BROADCAST);
        registerReceiver(mAlarmReceiver, filter);

        Intent intent = new Intent(this, MyService.class);
        startService(intent);

        main_search = (ImageView) findViewById(R.id.main_search);
        main_search.setOnClickListener(this);

        main_tablayout = (TabLayout) findViewById(R.id.main_tablayout);

        main_tablayout.setSelectedTabIndicatorColor(0xffffffff);
        main_tablayout.setTabTextColors(0xffffffff, 0xffeef203);

        FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
        main_viewpager = (ViewPager) findViewById(R.id.main_viewpager);
        main_viewpager.setAdapter(adapter);
        main_viewpager.addOnPageChangeListener(this);
        main_tablayout.setupWithViewPager(main_viewpager);

    }

    /**
     * 换皮肤方法
     */
    @Override
    protected void onResume() {
        mSettingManager = new SkinSettingManager(MainActivity.this, layout);
        mSettingManager.initSkins();

        int[] imageResource = {R.mipmap.sun, R.mipmap.lan, R.mipmap.mai_1, R.mipmap.lan, R.mipmap.mai_1, R.mipmap.lan};
        int indexImage = mSettingManager.getSkinType();
        if (indexImage >= 0) {

            layout.setBackgroundResource(imageResource[indexImage]);
        }

//        int mMode = BaseApplication.getMode();//Base setMode
//
//

//       switch (mMode) {
//           case 0://第一张图片
//               MySkinActivity mySkinActivity = new MySkinActivity();
//               break;
//           case 1://第二张图片
//               break;
//       }
       super.onResume();
    }

//        switch (mMode){
//            case 0://第一张图片
//                MySkinActivity mySkinActivity = new MySkinActivity();
//                break;
//            case 1://第二张图片
//                break;
//        }
//        super.onResume();
//
//     }
//    }
// }




    private void setUpMenu() {
        main_menu = (ImageView) findViewById(R.id.main_menu);
        main_menu.setOnClickListener(this);

        // attach to current activity;
        main_residemenu = new ResideMenu(this);

        // 设置resideMenu背景色
        //main_residemenu.setBackground(R.color.resideMenu_bg);
        main_residemenu.attachToActivity(this);
        main_residemenu.setMenuListener(menuListener);

        // valid scale factor is between 0.0f and 1.0f. leftmenu'width is
        // 150dip.
        main_residemenu.setScaleValue(0.5f);

        // 禁止使用右侧菜单
        main_residemenu.setDirectionDisable(ResideMenu.DIRECTION_RIGHT);

        // create menu items;

        itemLucency = new ResideMenuItem(this, R.mipmap.lucencyttt, "透明模式");
        itemWallpaper = new ResideMenuItem(this, R.mipmap.shakephonett, "一摇一切");
        itemSetting = new ResideMenuItem(this, R.mipmap.cleartt, "清除缓存");
        itemSleep = new ResideMenuItem(this, R.mipmap.sleeptimett, "睡眠模式");
        itemExit = new ResideMenuItem(this, R.mipmap.exittt, "退出应用");


        main_residemenu.addMenuItem(itemLucency, ResideMenu.DIRECTION_LEFT);
        main_residemenu.addMenuItem(itemWallpaper, ResideMenu.DIRECTION_LEFT);
        main_residemenu.addMenuItem(itemSetting, ResideMenu.DIRECTION_LEFT);
        main_residemenu.addMenuItem(itemSleep, ResideMenu.DIRECTION_LEFT);
        main_residemenu.addMenuItem(itemExit, ResideMenu.DIRECTION_LEFT);


        //  AseoZdpAseo.init(this, AseoZdpAseo.SCREEN_TYPE);

    }

    private void setListener() {

        //  main_residemenu.addMenuInfo(info);

        itemWallpaper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (BaseApplication.isShake) {
//                    Toast.makeText(MainActivity.this, "摇一摇关闭", Toast.LENGTH_SHORT).show();
//
//                } else {
                    Intent intent = new Intent(MyService.BROADCAST_SHAKE);
                    intent.putExtra(MyService.SHAKE_ON_OFF, itemWallpaper.isClickable());
                    sendBroadcast(intent);
                    Toast.makeText(MainActivity.this, "摇一摇开启", Toast.LENGTH_SHORT).show();
                    BaseApplication.isShake = itemWallpaper.isClickable();
//                }

            }
        });
        // 透明模式
        itemLucency.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeViewMode();
            }
        });

//        itemSetting.setOnClickListener(this);

        itemSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                   size = DataCleanManager.getCacheSize(getCacheDir());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                DataCleanManager.deleteFolderFile(getCacheDir().toString(), true);
                Toast.makeText(MainActivity.this, "已清理: " + size, Toast.LENGTH_LONG).show();
            }
        });





        // 睡眠模式
        itemSleep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSleepDialog();
            }
        });
        // 退出应用
        itemExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseApplication.getInstance().exit();
            }
        });

        //  info.setOnClickListener(this);

        main_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                main_residemenu.openMenu(ResideMenu.DIRECTION_LEFT);
            }
        });
    }

    /**
     * 改变夜间模式
     */
    void changeViewMode() {
        boolean isNight = getApp().isNightMode();
        if (isNight)
            ChangeToDay();
        else
            ChangeToNight();

        recreate();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_menu:
                main_residemenu.openMenu(ResideMenu.DIRECTION_LEFT);
                break;
            case R.id.main_search:
                Intent intent = new Intent(MainActivity.this, SearchActivity.class);
                startActivity(intent);
                break;
        }
    }

    private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
        @Override
        public void openMenu() {
            is_closed = false;
            main_menu.setVisibility(View.GONE);
        }

        @Override
        public void closeMenu() {
            is_closed = true;
            main_menu.setVisibility(View.VISIBLE);
        }
    };


    public ResideMenu getResideMenu() {
        return main_residemenu;
    }

    // 监听手机上的BACK键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 判断菜单是否关闭
            if (is_closed) {
                // 判断两次点击的时间间隔（默认设置为2秒）
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Toast.makeText(this, "再按一次返回到桌面", Toast.LENGTH_SHORT).show();

                    mExitTime = System.currentTimeMillis();
                } else {
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addCategory(Intent.CATEGORY_HOME);

                    startActivity(intent);
                }
            } else {
                main_residemenu.closeMenu();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        if (position == 0)
            main_residemenu.clearIgnoredViewList();
        else {
            main_residemenu.addIgnoredView(main_viewpager);
        }
    }


    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public void setSelectedFragment(BackHandledFragment selectedFragment) {
        this.mBackHandedFragment = selectedFragment;
    }

    @Override
    public void onBackPressed() {
        if (mBackHandedFragment == null) {
            if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
                super.onBackPressed();
            } else {
                getSupportFragmentManager().popBackStack();
            }
        }
    }

    // 注册广播
    public void register() {
        receiver = new ServiceReceiver();
        IntentFilter intentFilter = new IntentFilter();
        // 上一曲
        intentFilter.addAction(ServiceReceiver.NOTIFICATION_ITEM_BUTTON_LAST);
        // 播放或暂停
        intentFilter.addAction(ServiceReceiver.NOTIFICATION_ITEM_BUTTON_PLAY);
        // 下一曲
        intentFilter.addAction(ServiceReceiver.NOTIFICATION_ITEM_BUTTON_NEXT);

        registerReceiver(receiver, intentFilter);
    }


    public void showSleepDialog() {

        if (BaseApplication.mIsSleepClockSetting) {
            cancleSleepClock();
            Toast.makeText(getApplicationContext(), "取消睡眠模式成功。。。",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        View view = View.inflate(this, R.layout.sleep_time, null);
        final Dialog dialog = new Dialog(this, R.style.lrc_dialog);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);

        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        // lp.x = 100; // 新位置X坐标
        // lp.y = 100; // 新位置Y坐标
        lp.width = (int) (mScreenWidth * 0.7); // 宽度
        // lp.height = 400; // 高度

        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setAttributes(lp);

        dialog.show();

        final Button cancleBtn = (Button) view.findViewById(R.id.cancle_btn);
        final Button okBtn = (Button) view.findViewById(R.id.ok_btn);
        final EditText timeEt = (EditText) view.findViewById(R.id.time_et);
        View.OnClickListener listener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v == cancleBtn) {
                    dialog.dismiss();
                } else if (v == okBtn) {
                    String timeS = timeEt.getText().toString();
                    if (TextUtils.isEmpty(timeS)
                            || Integer.parseInt(timeS) == 0) {
                        Toast.makeText(getApplicationContext(), "输入无效。。。",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    setSleepClock(timeS);
                    dialog.dismiss();
                }
            }
        };

        cancleBtn.setOnClickListener(listener);
        okBtn.setOnClickListener(listener);
    }

    /**
     * 设置睡眠闹钟
     *
     * @param timeS
     */
    private void setSleepClock(String timeS) {
        Intent intent = new Intent(ALARM_CLOCK_BROADCAST);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                MainActivity.this, 0, intent, 0);
        // 设置time时间之后退出程序
        int time = Integer.parseInt(timeS);
        long longTime = time * 60 * 1000L;
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC, System.currentTimeMillis() + longTime,
                pendingIntent);
        BaseApplication.mIsSleepClockSetting = true;
        Toast.makeText(getApplicationContext(), "将在" + timeS + "分钟后退出应用。。。", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * 取消睡眠闹钟
     */
    private void cancleSleepClock() {
        Intent intent = new Intent(ALARM_CLOCK_BROADCAST);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                MainActivity.this, 0, intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.cancel(pendingIntent);
        BaseApplication.mIsSleepClockSetting = false;
    }

    private BroadcastReceiver mAlarmReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            //退出程序
            BaseApplication.getInstance().exit();
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mAlarmReceiver);
        unregisterReceiver(receiver);
        cancleSleepClock();
    }
}